package org.shzhyun.tools;
import java.io.ByteArrayInputStream;
import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class Program {
	
    public static void save(float[] buffer,double sampleRate,int channels,File outs) throws Exception {
        
    	//if(sampleRate ==0.0){
//        	 sampleRate = 22050.0;
            sampleRate = 2205.0;
        //} 

        final byte[] byteBuffer = new byte[buffer.length * 2];

        int bufferIndex = 0;
        for (int i = 0; i < byteBuffer.length; i++) {
            final int x = (int)(buffer[bufferIndex++] ); //* 32767.0

            byteBuffer[i++] = (byte)x;
            byteBuffer[i] = (byte)(x >>> 8);
        }
        
        //临时文件效果不好
        //File out = File.createTempFile("audio_example", ".wav");  
         
        final boolean bigEndian = false;
        final boolean signed = true;

        final int bits = 16;
        if(channels ==0){
        	 channels = 1;
        } 

        AudioFormat format = new AudioFormat((float)sampleRate, bits, channels, signed, bigEndian);
        ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer);
        AudioInputStream audioInputStream = new AudioInputStream(bais, format, buffer.length);
        AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outs);
        bais.close();
        audioInputStream.close();
        audioInputStream.close(); 
        /*Thread.sleep(2000);
        File outs = new File(path+"/audio_example.wav");
        SoundPlay sound = new SoundPlay(outs);
        sound.play();*/
         
    }
}